import json
from django.http import JsonResponse, FileResponse
from django.shortcuts import render, HttpResponse
import time
from business.models import ICE, GasBoiler, ElectricBoiler, AR, IceTank, ERU, AirPump, GroundPump, GasTurbine, WindPower, PVP, ARS, Buttery, \
    CalResult, DesignPlan
from users.models import Users
from DataPlatform.settings import STATIC_ROOT
from django.utils.encoding import escape_uri_path
import os
from .calculate import CalThread
from django.db.models import Sum, Max
import threading
import traceback
from users.tools.net_tools import session_check

# Create your views here.

"""
该文件中，主要保存的是对外的接口方法，对外的请求协议为Http中的get、post两种
该方法的定义与同路径下的url文件相对应，对外的名称为url中的名称，实际的调用为对应到本文件中的方法名称
"""


def add_devices(request):
    """
    添加设备方法
    如果http请求为POST，则根据传入参数添加设备。
    """
    if request.method == 'POST':
        # 首先，获取所有post参数，并将字符串类型的参数转化为json格式
        ask = json.loads(str(request.body, encoding='UTF-8'))
        # 其次，获取参数中设备的类型
        cat = ask['catalog']
        # 然后获取设备的名称
        model_name = ask['devices']['model_name']
        result = {
            'code': 200,
            'msg': 'ok'
        }
        # 这里判断参数中是否存在类别与设备名称
        # 获取设备名称的主要用途在于判断是否设备库中已经存在相同型号的设备
        # 如果存在，将不允许新增设备（设备型号在同类型下唯一）
        if (not cat) or (not model_name):
            result['code'] = 500
            result['msg'] = '请输入设备类型和设备型号'
            return JsonResponse(result)
        try:
            # 以内燃机为例：
            # 首先判断类别是否为内燃机
            # 其次查看数据库中是否存在设备名称
            # 如果以上均通过校验，则保存相应参数；如没有通过，则返回识别码501并提示'已存在该型号设备'
            if cat == 'ICE':
                # 内燃机
                if not ICE.objects.filter(model_name=model_name).exists():
                    ICE(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'GB':
                # 燃气锅炉
                if not GasBoiler.objects.filter(model_name=model_name).exists():
                    GasBoiler(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'EB':
                if not ElectricBoiler.objects.filter(model_name=model_name).exists():
                    ElectricBoiler(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'AR':
                if not AR.objects.filter(model_name=model_name).exists():
                    AR(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'IT':
                if not IceTank.objects.filter(model_name=model_name).exists():
                    IceTank(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'ERU':
                if not ERU.objects.filter(model_name=model_name).exists():
                    ERU(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'AP':
                if not AirPump.objects.filter(model_name=model_name).exists():
                    AirPump(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'GP':
                if not GroundPump.objects.filter(model_name=model_name).exists():
                    GroundPump(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'GT':
                if not GasTurbine.objects.filter(model_name=model_name).exists():
                    GroundPump(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'WP':
                if not WindPower.objects.filter(model_name=model_name).exists():
                    WindPower(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'PVP':
                if not PVP.objects.filter(model_name=model_name).exists():
                    PVP(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'ARS':
                if not ARS.objects.filter(model_name=model_name).exists():
                    ARS(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            elif cat == 'BU':
                if not Buttery.objects.filter(model_name=model_name).exists():
                    ARS(**ask['devices']).save()
                else:
                    result['code'] = 501
                    result['msg'] = '已存在该型号设备'
            else:
                raise ValueError()
        except Exception as e:
            print(e)
            traceback.print_exc()
            result['code'] = 500
            result['msg'] = '存储错误，请检查设备类型和参数名称'
        return JsonResponse(result)


def update_device(request):
    """
    更新设备方法，与添加类似，即校验类别与型号名称，如通过校验，更新设备型号下的参数为新传入参数，否则提示错误信息
    :param request:
    :return:
    """
    if request.method == 'POST':
        ask = json.loads(str(request.body, encoding='UTF-8'))
        result = {
            'code': 200,
            'msg': 'ok'
        }

        cat = ask['catalog']
        model_name = ask['devices']['model_name']
        params = ask['devices']
        if not cat or not model_name:
            result['code'] = 500
            result['msg'] = "请输入设备类型和型号"
            return JsonResponse(result)

        try:
            if cat == 'ICE':
                # 内燃机
                target = ICE.objects.get(model_name=model_name)
                if target:
                    target.max_power = params['max_power']
                    target.heat_production = params['heat_production']
                    target.power_generation = params['power_generation']
                    target.heat_effect = params['heat_effect']
                    target.power_effect = params['power_effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        ICE.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'GB':
                # 燃气锅炉
                target = GasBoiler.objects.get(model_name=model_name)
                if target:
                    target.max_in_power = params['max_in_power']
                    target.out_power = params['out_power']
                    target.heat_effect = params['heat_effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        GasBoiler.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'EB':
                target = ElectricBoiler.objects.get(model_name=model_name)
                if target:
                    target.max_in_power = params['max_in_power']
                    target.max_out_power = params['max_out_power']
                    target.heat_effect = params['heat_effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        ElectricBoiler.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'AR':
                target = AR.objects.get(model_name=model_name)
                if target:
                    target.cool_cap = params['cool_cap']
                    target.heat_cap = params['heat_cap']
                    target.income_pressure = params['income_pressure']
                    target.pay_to_cool = params['pay_to_cool']
                    target.pay_to_heat = params['pay_to_heat']
                    target.income_cool = params['income_cool']
                    target.income_heat = params['income_heat']
                    target.heat_effect = params['heat_effect']
                    target.cool_effect = params['cool_effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        AR.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'IT':
                target = IceTank.objects.get(model_name=model_name)
                if target:
                    target.heat_capacity = params['heat_capacity']
                    target.storage = params['storage']
                    target.effect = params['effect']
                    target.max_prop = params['max_prop']
                    target.min_prop = params['min_prop']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']

                    if int(params['is_default']) == 1:
                        IceTank.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'ERU':
                target = ERU.objects.get(model_name=model_name)

                if target:
                    target.ice_effect = params['ice_effect']
                    target.cool_effect = params['cool_effect']
                    target.power_to_ice = params['power_to_ice']
                    target.power_to_cool = params['power_to_cool']
                    target.input_ice_power = params['input_ice_power']
                    target.input_cool_power = params['input_cool_power']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']

                    if int(params['is_default']) == 1:
                        ERU.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'AP':
                target = AirPump.objects.get(model_name=model_name)
                if target:
                    target.make_cool_power = params['make_cool_power']
                    target.input_power = params['input_power']
                    target.effect = params['effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']

                    if int(params['is_default']) == 1:
                        AirPump.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'GP':
                target = GroundPump.objects.get(model_name=model_name)
                if target:
                    target.output_cool_power = params['output_cool_power']
                    target.input_cool_power = params['input_cool_power']
                    target.make_cool_effect = params['make_cool_effect']
                    target.output_heat_power = params['output_heat_power']
                    target.input_heat_power = params['input_heat_power']
                    target.make_heat_effect = params['make_heat_effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']

                    if int(params['is_default']) == 1:
                        GroundPump.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'GT':
                target = GasTurbine.objects.get(model_name=model_name)
                if target:
                    target.input_power = params['input_power']
                    target.generation_power = params['generation_power']
                    target.generation_effect = params['generation_effect']
                    target.waste_heat = params['waste_heat']
                    target.heat_effect = params['heat_effect']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        GasTurbine.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'WP':
                target = WindPower.objects.get(model_name=model_name)
                if target:
                    target.s2 = params['s2']
                    target.s3 = params['s3']
                    target.s4 = params['s4']
                    target.s5 = params['s5']
                    target.s6 = params['s6']
                    target.s7 = params['s7']
                    target.s8 = params['s8']
                    target.s9 = params['s9']
                    target.s10 = params['s10']
                    target.s11 = params['s11']
                    target.s12 = params['s12']
                    target.s13 = params['s13']
                    target.s14 = params['s14']
                    target.s15 = params['s15']
                    target.s16 = params['s16']
                    target.s17 = params['s17']
                    target.s18 = params['s18']
                    target.s19 = params['s19']
                    target.s20 = params['s20']
                    target.s21 = params['s21']
                    target.s22 = params['s22']
                    target.s23 = params['s23']
                    target.s24 = params['s24']
                    target.s25 = params['s25']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']

                    if int(params['is_default']) == 1:
                        WindPower.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'PVP':
                target = PVP.objects.get(model_name=model_name)
                if target:
                    target.max_power = params['cool_cap']
                    target.ppp = params['ppp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        PVP.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'ARS':
                target = ARS.objects.get(model_name=model_name)
                if target:
                    target.cool_cap = params['cool_cap']
                    target.effect = params['effect']
                    target.input_power = params['input_power']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        PVP.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            elif cat == 'BU':
                target = Buttery.objects.get(model_name=model_name)
                if target:
                    target.capacity = params['capacity']
                    target.rv = params['rv']
                    target.uv = params['uv']
                    target.dv = params['dv']
                    target.u_cdp = params['u_cdp']
                    target.l_cdp = params['l_cdp']
                    target.u_scr = params['u_scr']
                    target.l_scr = params['l_scr']
                    target.effect = params['effect']
                    target.ppu = params['ppu']
                    target.sp = params['sp']
                    target.is_default = params['is_default']
                    if int(params['is_default']) == 1:
                        PVP.objects.filter(is_default=True).update(is_default=False)
                    target.save()
                else:
                    result['code'] = 501
                    result['msg'] = '该型号设备不存在，请检查'
            else:
                result['code'] = 500
                result['msg'] = '设备类型错误，请检查。'
        except Exception as e:
            repr(e)
            print(e)
            result['code'] = 501
            result['msg'] = '存储错误，请检查设备类型和参数名称'
        return JsonResponse(result)


def delete_device(request):
    """
    删除设备方法，通过类型与设备型号进行删除。
    :param request:
    :return:
    """
    if request.method == 'POST':
        ask = json.loads(str(request.body, encoding='UTF-8'))
        result = {
            'code': 200,
            'msg': 'ok'
        }

        cat = ask['catalog']
        model_name = ask['targets']
        try:
            if not model_name or not cat:
                raise ValueError('Wrong catalog or model_name')
            search = ICE.objects
            if cat == 'ICE':
                search = ICE.objects.get(model_name__in=model_name)
            elif cat == 'GB':
                # 燃气锅炉
                search = GasBoiler.objects.filter(model_name__in=model_name)
            elif cat == 'EB':
                search = ElectricBoiler.objects.filter(model_name__in=model_name)
            elif cat == 'AR':
                search = AR.objects.filter(model_name__in=model_name)
            elif cat == 'IT':
                search = IceTank.objects.filter(model_name__in=model_name)
            elif cat == 'ERU':
                search = ERU.objects.filter(model_name__in=model_name)
            elif cat == 'AP':
                search = AirPump.objects.filter(model_name__in=model_name)
            elif cat == 'GP':
                search = GroundPump.objects.filter(model_name__in=model_name)
            elif cat == 'PVP':
                search = PVP.objects.filter(model_name__in=model_name)
            elif cat == 'ARS':
                search = ARS.objects.filter(model_name__in=model_name)
            else:
                result['code'] = 501
                result['msg'] = '删除的类型不正确，请检查搜索设备的类型'

            search.delete()
        except Exception as e:
            repr(e)
            result['code'] = 501
            result['msg'] = str(e)
        else:
            result['code'] = 200
            result['msg'] = "删除成功"
        finally:
            return JsonResponse(result)


def show_devices(request):
    """
    展示设备的方法，用于展示设备页面
    :param request:
    :return:
    """
    return render(request, 'business/drivers.html')


def config_calculate(request):
    """
    用过展示计算配置的页面的方法
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'business/models.html')


# def show_index(request):
#     """
#     展示登录后内容区域的页面的代码，由于暂时由该账号最后一次计算的结果为展示内容，该方法暂停使用
#     :param request:
#     :return:
#     """
#     return render(request, 'users/index.html')

"""
以下以show_（设备类型）命名的方法，均为展示设备列表的相关内容
由于该方法通过get进行判断，所以会校验get方法中的is_single参数
如果为true，则返回适用于弹窗的html，否则将返回适用于查看设备的html
"""


def show_ice(request):
    """显示内燃机 Internal combustion engine"""
    is_single = request.GET.get('single', '')

    rsp = {
        'which': "内燃机",
        'cat': 'ICE',
        'devices': ICE.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "max_power": "最大功率(kW)",
            "heat_production": "产热量(kW)",
            "power_generation": "发电量(kW)",
            "heat_effect": "热效率(%)",
            "power_effect": "电效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_ice.html', rsp)
    else:
        return render(request, 'business/device_ice.html', rsp)


def show_gb(request):
    """显示燃气锅炉"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "燃气锅炉",
        'cat': 'GB',
        'devices': GasBoiler.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "max_in_power": "最大输入功率(kW)",
            "out_power": "输出功率(kW)",
            "heat_effect": "热效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_gb.html', rsp)
    else:
        return render(request, 'business/device_gb.html', rsp)


def show_eb(request):
    """显示电锅炉"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "电锅炉",
        'cat': 'EB',
        'devices': ElectricBoiler.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "max_in_power": "最大输入功率(kW)",
            "max_out_power": "最大输出功率(kW)",
            "heat_effect": "热效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_eb.html', rsp)
    else:
        return render(request, 'business/device_eb.html', rsp)


def show_ar(request):
    """显示吸收式制冷机"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "吸收式制冷机",
        'cat': 'AR',
        'devices': AR.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "cool_cap": "制冷量(kW)",
            "heat_cap": "供热量(kW)",
            "income_pressure": "进口压力(kPa.G)",
            "pay_to_cool": "耗量(制冷)(m<sup>3</sup>/h)",
            "pay_to_heat": "耗量(制热)(m<sup>3</sup>/h)",
            "income_cool": "制冷输入功率(kW)",
            "income_heat": "制热输入功率(kW)",
            "heat_effect": "制热效率(%)",
            "cool_effect": "制冷效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_ar.html', rsp)
    else:
        return render(request, 'business/device_ar.html', rsp)


def show_ice_tank(request):
    """显示蓄冰槽"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "蓄冰槽",
        'cat': 'IT',
        'devices': IceTank.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "heat_capacity": "蓄冰潜热容量(kW)",
            "storage": "蓄冰槽容量(L)",
            "effect": "充放能效率(%)",
            "max_prop": "储能占比上限(%)",
            "min_prop": "储能占比上限(%)",
            "ppp": "单位功率费用(元/kWh)",
        }
    }
    if is_single:
        return render(request, 'business/table_ice_tank.html', rsp)
    else:
        return render(request, 'business/device_ice_tank.html', rsp)


def show_eru(request):
    """显示电制冷机组"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "电制冷机组",
        'cat': 'ERU',
        'devices': ERU.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "ice_effect": "制冰效率(%)",
            "cool_effect": "制冷效率(%)",
            "power_to_ice": "制冰功率(kW)",
            "power_to_cool": "制冷功率(kW)",
            "input_ice_power": "制冰输入功率(kW)",
            "input_cool_power": "制冷输入功率(kW)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_eru.html', rsp)
    else:
        return render(request, 'business/device_eru.html', rsp)


def show_air_pump(request):
    """显示风冷热泵"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "风冷热泵",
        'cat': 'AP',
        'devices': AirPump.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "make_cool_power": "制冷量(kW)",
            "input_power": "制冷输入功率(kW)",
            "effect": "效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_air_pump.html', rsp)
    else:
        return render(request, 'business/device_air_pump.html', rsp)


def show_gp(request):
    """显示地源热泵"""
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "地源热泵",
        'cat': 'GP',
        'devices': GroundPump.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "output_cool_power": "输出冷量(kW)",
            "input_cool_power": "制冷输入功率(kW)",
            "make_cool_effect": "制冷效率(%)",
            "output_heat_power": "输出热量(kW)",
            "input_heat_power": "制热输入功率(kW)",
            "make_heat_effect": "制热效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_gp.html', rsp)
    else:
        return render(request, 'business/device_gp.html', rsp)


def show_gt(request):
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "燃气轮机",
        'cat': 'GT',
        'devices': GasTurbine.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "input_power": "输入功率(kW)",
            "generation_power": "发电功率(kW)",
            "generation_effect": "发电效率(%)",
            "waste_heat": "余热(kW)",
            "heat_effect": "热效率(%)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_gt.html', rsp)
    else:
        return render(request, 'business/device_gt.html', rsp)


def show_wp(request):
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "风机",
        'cat': 'WP',
        'devices': WindPower.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "s2": "风速2.5出力(kW)",
            "s3": "风速3出力(kW)",
            "s4": "风速4出力(kW)",
            "s5": "风速5出力(kW)",
            "s6": "风速6出力(kW)",
            "s7": "风速7出力(kW)",
            "s8": "风速8出力(kW)",
            "s9": "风速9出力(kW)",
            "s10": "风速10出力(kW)",
            "s11": "风速11出力(kW)",
            "s12": "风速12出力(kW)",
            "s13": "风速13出力(kW)",
            "s14": "风速14出力(kW)",
            "s15": "风速15出力(kW)",
            "s16": "风速16出力(kW)",
            "s17": "风速17出力(kW)",
            "s18": "风速18出力(kW)",
            "s19": "风速19出力(kW)",
            "s20": "风速20出力(kW)",
            "s21": "风速21出力(kW)",
            "s22": "风速22出力(kW)",
            "s23": "风速23出力(kW)",
            "s24": "风速24出力(kW)",
            "s25": "风速25出力(kW)",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_wp.html', rsp)
    else:
        return render(request, 'business/device_wp.html', rsp)


def show_pvp(request):
    is_single = request.GET.get('single', '')
    rsp = {
        'which': '光伏板',
        'cat': 'PVP',
        'devices': PVP.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "max_power": "最大功率",
            "ppp": "单位功率费用(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_pvp.html', rsp)
    else:
        return render(request, 'business/device_pvp.html', rsp)


def show_ars(request):
    is_single = request.GET.get('single', '')
    rsp = {
        'which': "烟气热水机",
        'cat': 'ARS',
        'devices': ARS.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "型号名称",
            "cool_cap": "制冷量(kW)",
            "effect": "制冷效率(%)",
            "input_power": "输入功率"
        }
    }
    if is_single:
        return render(request, 'business/table_ars.html', rsp)
    else:
        return render(request, 'business/device_ars.html', rsp)


def show_buttery(request):
    is_single = request.GET.get('single', '')
    rsp = {
        'which': '蓄电池',
        'cat': 'BU',
        'devices': Buttery.objects.all().order_by('-is_default'),
        'params': {
            "model_name": "设备型号",
            "capacity": "配置容量(kWh)",
            "rv": "额定电压(V)",
            "uv": "下限电压(V)",
            "dv": "上限电压(V)",
            "u_cdp": "充放功率上限(kW)",
            "l_cdp": "充放功率下限(kW)",
            "u_scr": "储能占比上限(%)",
            "l_scr": "储能占比下限(%)",
            "effect": "充放效率(%)",
            "ppu": "单位容量价格(元/kWh)",
            "sp": "系统投资(元/kW)",
        }
    }
    if is_single:
        return render(request, 'business/table_bu.html', rsp)
    else:
        return render(request, 'business/device_bu.html', rsp)


# ======================展示设备方法结束====================


def get_params_file(request):
    """
    用于获取计算配置文件的方法，通过get方法中的参数判断获取的是哪一种excel文件
    如果判断正确，则浏览器会直接进行下载，否则会返回请求数据错误
    :param request:
    :return:
    """
    which = request.GET.get('which', '')
    if which == 'load':
        path = 'data_target.xlsx'
        file_name = '全年负载及相关费率'
    elif which == 'wind':
        path = 'wind.xlsx'
        file_name = '风力发电数据'
    elif which == 'light':
        path = 'light.xlsx'
        file_name = '光伏发电数据'
    else:
        return HttpResponse('请求数据错误')

    rsp = FileResponse(open(STATIC_ROOT + '/business/params_file/' + path, 'rb'))
    rsp['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name + '.xlsx'))
    return rsp


@session_check
def get_his_file(request):
    """
    获取计算历史数据，包括：负载文件，风力参数，光伏参数，经济评价参数以及计算结果
    获取方式为：通过用户账号，文件类型以及计算唯一识别码进行组合后，即可获取到历史文件
    :param request:
    :return:
    """
    who = request.COOKIES.get('who', '')
    catalog = request.GET.get('catalog', '')
    mark = request.GET.get('mark', '')
    if catalog == 'load':
        file_name = '全年负载及相关费率'
    elif catalog == 'wind':
        file_name = '风力发电数据'
    elif catalog == 'light':
        file_name = '光伏发电数据'
    elif catalog == 'economic':
        file_name = '经评数据'
    elif catalog == 'result':
        file_name = '计算结果'
    else:
        file_name = ''

    if who and file_name:
        target_file_path = os.path.join(STATIC_ROOT + '/business/user_params_file/', who + "_" + catalog + "_" + mark)
        rsp = FileResponse(open(target_file_path + '.xlsx', 'rb'))
        rsp['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name + '.xlsx'))
        return rsp
    else:
        return HttpResponse("目标文件缺失，请联系管理员")


@session_check
def upload_params_file(request):
    """
    将用户下载后填写完成的负载文件，风资源，光资源文件进行保存：保存地址为：STATIC_ROOT + '/business/user_params_file/
    其中STATIC_ROOT为配置文件中定义的文件路径
    :param request:
    :return:
    """
    rst = {
        'code': 200,
        'msg': ''
    }

    timeStamp = int(time.time())

    load_file = request.FILES.get("load_file", None)  # 获取上传的文件，如果没有文件，则默认为None
    wind_file = request.FILES.get("wind_file", None)  # 获取上传的文件，如果没有文件，则默认为None
    light_file = request.FILES.get("light_file", None)  # 获取上传的文件，如果没有文件，则默认为None
    who = request.COOKIES.get('who')
    try:
        if not load_file:
            rst['code'] = 500
            rst['msg'] = '上传文件为空！'
            return JsonResponse(rst)
        else:
            destination = open(os.path.join(STATIC_ROOT + '/business/user_params_file/', who + '_load_' + str(timeStamp) + '.xlsx'),
                               'wb+')  # 打开特定的文件进行二进制的写操作
            for chunk in load_file.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()

        if wind_file:
            destination = open(os.path.join(STATIC_ROOT + '/business/user_params_file/', who + '_wind_' + str(timeStamp) + '.xlsx'),
                               'wb+')  # 打开特定的文件进行二进制的写操作
            for chunk in wind_file.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()

        if light_file:
            destination = open(os.path.join(STATIC_ROOT + '/business/user_params_file/', who + '_light_' + str(timeStamp) + '.xlsx'),
                               'wb+')  # 打开特定的文件进行二进制的写操作
            for chunk in light_file.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()
    except Exception as e:
        print(e)
        rst['code'] = 501
        rst['msg'] = '存储错误，请联系管理员'
    else:
        rst['mark'] = str(timeStamp)
    rst['mark'] = str(timeStamp)
    return JsonResponse(rst)


# 记录所有子线程的字典类型（全局）
cal_dict = {}


@session_check
def start_calculate(request):
    """
    进行规划的方法：
    :param request:
    :return:
    """
    rst = {
        'code': 200,
        'msg': ''
    }
    who = request.COOKIES.get('who', '')
    ask = json.loads(str(request.body, encoding='UTF-8'))
    mark = ask['mark']
    params = ask['params']
    economic_data = ask['economic']
    data_file = who + '_load_' + mark + '.xlsx'
    wind_file = who + '_wind_' + mark + '.xlsx'
    light_file = who + '_light_' + mark + '.xlsx'

    solar_path = ''
    wind_path = ''

    root_path = STATIC_ROOT + '/business/user_params_file/'
    # 首先会将配置规划的数据进行解析
    check_params = json.loads(params)
    # 然后检查是否存在负载文件
    if os.path.exists(os.path.join(root_path, data_file)):

        pass
    else:
        rst['code'] = 500
        rst['msg'] = '负载文件异常，请联系管理员'
        return JsonResponse(rst)
    # 然后校验是否配置中有风力选项，如果有则检查是否存在上传风资源文件
    if check_params['re']['wind']['is_selected'] == 1:
        if not os.path.exists(os.path.join(root_path, wind_file)):
            rst['code'] = 500
            rst['msg'] = '未上传风机参数'
            return JsonResponse(rst)
        else:
            wind_path = os.path.join(root_path, wind_file)

    # 类似的检查，用于校验是否存在光资源文件
    if check_params['re']['solar']['is_selected'] == 1:
        if not os.path.exists(os.path.join(root_path, light_file)):
            rst['code'] = 500
            rst['msg'] = '未上传光伏设备参数'
            return JsonResponse(rst)
        else:
            solar_path = os.path.join(root_path, light_file)

    # 如果通过以上校验，则将配置信息传入数据库中
    save_params(who, check_params, mark)

    # 由于计算极为耗时，所以此处开启线程进行处理，顺便将线程保存至全局变量中，方便获取计算进度
    cal_thread = CalThread(params, os.path.join(root_path, data_file), solar_path, wind_path, mark, economic_data, who)
    cal_thread.name = who + "_" + str(mark)
    cal_dict[cal_thread.name] = cal_thread
    cal_thread.start()
    # =====线程启动结束=========
    return JsonResponse(rst)


@session_check
def get_calculate_schedule(request):
    """
    获取计算进度的方法，用于开始规划后，查看规划的进度
    :param request:
    :return:
    """
    rst = {
        'code': 200,
        'msg': ''
    }
    mark = request.GET.get('mark', '')
    who = request.COOKIES.get('who', '')
    target_name = who + "_" + str(mark)
    all_live_thread = [i.name for i in threading.enumerate()]
    # rst = None
    if target_name in cal_dict.keys() and target_name in all_live_thread:
        rst['schedule'], rst['msg'] = cal_dict[target_name].get_result()
    elif target_name in cal_dict.keys() and target_name not in all_live_thread:
        rst['msg'] = '已完成计算！'
    else:
        rst['code'] = 500
        rst['msg'] = '无效的计算'
    return JsonResponse(rst)


@session_check
def get_supply_data(request):
    """
    将数据库中典型日的第一幅柱状图的数据返回给前端进行展示
    :param request:
    :return:
    """
    """展示供冷、供热的设备出力柱状图"""
    who = request.COOKIES.get('who', '')
    which_day = request.GET.get('which', '')
    which_plan = request.GET.get('which_plan', '')
    rst = {
        'code': 200,
        'msg': '',
        'data': ''
    }

    if which_day == "0":
        plan_date = DesignPlan.objects.values('winter_day', 'cu_which', 'cu_is_selected').get(belongs__account=who, design_id=which_plan)
        data_target = CalResult.objects.values('gp_oh', 'cchp_oh', 'gb_oh', 'eb_oh', 'heat_buy', 'target_time').filter(
            target_date=plan_date['winter_day'], design_id=which_plan).order_by('-target_date')

        cal_data = {
            'legend': ['地源热泵', '三联供', '燃气锅炉', '电锅炉供热', '购热量'],
            'xAxis': [str(i) for i in range(1, 25)]
        }

        from copy import deepcopy
        template = {
            'name': '',
            'type': 'bar',
            'stack': '总量',
            'label': {
                'normal': {
                    'show': False,
                    'position': 'insideRight'
                }
            },
            'data': []
        }
        chat_data = []

        for i in range(len(cal_data['legend'])):
            item = deepcopy(template)
            item['name'] = cal_data['legend'][i]
            chat_data.append(item)

        for i in data_target:
            for index, j in enumerate(['gp_oh', 'cchp_oh', 'gb_oh', 'eb_oh', 'heat_buy']):
                chat_data[index]['data'].append(i[j])

        cal_data['chat_data'] = chat_data
        rst['data'] = cal_data
    elif which_day == "1":
        plan_date = DesignPlan.objects.values('summer_day').get(belongs__account=who, design_id=which_plan)
        data_target = CalResult.objects.values('gp_oc', 'ap_oc', 'cchp_oc', 'ar_oc', 'it_dis', 'target_time').filter(
            target_date=plan_date['summer_day'],
            design_id=which_plan).order_by('-target_date')

        cal_data = {
            'legend': ['地源热泵', '风冷热泵', '三联供', '吸收式制冷机制冷', '冰蓄冷'],
            'xAxis': [str(i) for i in range(1, 25)]
        }

        from copy import deepcopy
        template = {
            'name': '',
            'type': 'bar',
            'stack': '总量',
            'label': {
                'normal': {
                    'show': False,
                    'position': 'insideRight'
                }
            },
            'data': []
        }
        chat_data = []

        for i in range(len(cal_data['legend'])):
            item = deepcopy(template)
            item['name'] = cal_data['legend'][i]
            chat_data.append(item)

        for i in data_target:
            for index, j in enumerate(['gp_oc', 'ap_oc', 'cchp_oc', 'ar_oc', 'it_dis']):
                if index == 3 and 8 > (i['target_time'] % 24) >= 0:
                    chat_data[index]['data'].append(i[j] * -1)
                else:
                    chat_data[index]['data'].append(i[j])

        cal_data['chat_data'] = chat_data
        rst['data'] = cal_data
    else:
        rst['code'] = 500
        rst['msg'] = '错误日期，请检查'
        print('wrong params')

    return JsonResponse(rst)


@session_check
def get_line_data(request):
    """对比供冷、供热的出力"""
    which_day = request.GET.get('which', '')
    which_plan = request.GET.get('which_plan', '')
    who = request.COOKIES.get('who', 0)

    rsp = {
        'code': 200,
        'msg': '',
        'data': ''
    }
    plan_date = DesignPlan.objects.values('winter_day', 'summer_day').get(belongs__account=who, design_id=which_plan)

    if which_day == "0":
        data_target = CalResult.objects.values('gp_oh', 'cchp_oh', 'gb_oh', 'heat_load', 'heat_buy').filter(
            target_date=plan_date['winter_day'], design_id=which_plan).order_by('-target_date')
        cal_data = []
        for index, i in enumerate(data_target):
            device_data = {'time': str(index + 1), 'type': '设备出力', 'value': (i['gp_oh'] + i['cchp_oh'] + i['gb_oh'] + i['heat_buy'])}
            load_data = {'time': str(index + 1), 'type': '负载', 'value': i['heat_load']}
            cal_data.append(device_data)
            cal_data.append(load_data)
        rsp['data'] = cal_data
    elif which_day == '1':
        data_target = CalResult.objects.values('ar_oc', 'ap_oc', 'cchp_oc', 'gp_oc', 'it_dis', 'cold_load').filter(
            target_date=plan_date['summer_day'], design_id=which_plan).order_by('-target_date')
        cal_data = []
        for index, i in enumerate(data_target):
            device_data = {'time': str(index + 1), 'type': '设备出力',
                           'value': (i['ap_oc'] + i['cchp_oc'] + i['gp_oc'] + i['it_dis'] + i['ar_oc'])}
            load_data = {'time': str(index + 1), 'type': '负载', 'value': i['cold_load']}
            cal_data.append(device_data)
            cal_data.append(load_data)
        rsp['data'] = cal_data
    else:
        rsp['code'] = 500
        rsp['msg'] = '请求日期错误'
        return JsonResponse(rsp)

    return JsonResponse(rsp)


@session_check
def get_power_data(request):
    """
    用户返回电力数据的柱状图
    :param request:
    :return:
    """
    which_day = request.GET.get('which', '')
    which_plan = request.GET.get('which_plan', '')
    who = request.COOKIES.get('who', 0)

    rsp = {
        'code': 200,
        'msg': '',
        'data': ''
    }
    plan_date = DesignPlan.objects.values('winter_day', 'summer_day').get(belongs__account=who, design_id=which_plan)
    if which_day == "0":
        data_target = CalResult.objects.values('ele_buy', 'ice_os', 'wind_power', 'pvp_power', 'gp_ieh', 'ap_ie', 'eb_ie', 'it_ch',
                                               'ele_sell', 'ele_load').filter(
            target_date=plan_date['winter_day'], design_id=which_plan).order_by('-target_date')
    elif which_day == '1':
        data_target = CalResult.objects.values('ele_buy', 'ice_os', 'wind_power', 'pvp_power', 'gp_ieh', 'ap_ie', 'eb_ie', 'it_ch',
                                               'ele_sell', 'ele_load').filter(
            target_date=plan_date['summer_day'], design_id=which_plan).order_by('-target_date')
    else:
        rsp['code'] = 500
        rsp['msg'] = '请求日期错误'
        return JsonResponse(rsp)

    cal_data = {
        'legend': ['购电量', 'CCHP发电', '风机发电', '光伏发电', '地源热泵耗电', '风冷热泵耗电', '电锅炉耗电', '冷水机组耗电', '售电量', '用户电负荷'],
        'xAxis': [str(i) for i in range(1, 25)]
    }

    from copy import deepcopy
    template = {
        'name': '',
        'type': 'bar',
        'stack': '总量',
        'label': {
            'normal': {
                'show': False,
                'position': 'insideRight'
            }
        },
        'data': []
    }
    chat_data = []

    for i in range(len(cal_data['legend'])):
        item = deepcopy(template)
        item['name'] = cal_data['legend'][i]
        chat_data.append(item)

    for i in data_target:
        for index, j in enumerate(['ele_buy', 'ice_os', 'wind_power', 'pvp_power', 'gp_ieh', 'ap_ie', 'eb_ie', 'it_ch',
                                   'ele_sell', 'ele_load']):
            if index > 3:
                chat_data[index]['data'].append(-1 * i[j])
            else:
                chat_data[index]['data'].append(i[j])

    cal_data['chat_data'] = chat_data
    rsp['data'] = cal_data

    return JsonResponse(rsp)


@session_check
def get_power_sum(request):
    """对比供冷、供热的出力"""
    which_day = request.GET.get('which', '')
    which_plan = request.GET.get('which_plan', '')
    who = request.COOKIES.get('who', 0)

    rsp = {
        'code': 200,
        'msg': '',
        'data': ''
    }

    plan_date = DesignPlan.objects.values('winter_day', 'summer_day').get(belongs__account=who, design_id=which_plan)

    sum_data = CalResult.objects.values('ele_buy', 'ice_os', 'wind_power', 'pvp_power', 'gp_ieh', 'ap_ie', 'eb_ie', 'it_ch', 'ele_sell',
                                        'ele_load')

    if which_day == "0":
        cal_data = []
        data_target = sum_data.filter(target_date=plan_date['winter_day'], design_id=which_plan).order_by('-target_date')
    elif which_day == '1':
        cal_data = []
        data_target = sum_data.filter(target_date=plan_date['summer_day'], design_id=which_plan).order_by('-target_date')
    else:
        rsp['code'] = 500
        rsp['msg'] = '请求日期错误'
        return JsonResponse(rsp)

    for index, i in enumerate(data_target):
        device_data = {'time': str(index + 1), 'type': '供电量', 'value': (i['ele_buy'] + i['ice_os'] + i['wind_power'] + i['pvp_power'])}
        load_data = {'time': str(index + 1), 'type': '耗电量',
                     'value': (i['gp_ieh'] + i['ap_ie'] + i['eb_ie'] + i['it_ch'] + i['ele_sell'] + i['ele_load'])}
        cal_data.append(device_data)
        cal_data.append(load_data)
    rsp['data'] = cal_data

    return JsonResponse(rsp)


def save_params(account, params, d_id):
    """
    该方法用于解析用户传入的配置参数，并保存至数据库中
    :param account:
    :param params:
    :param d_id:
    :return:
    """
    dp = DesignPlan()
    dp.design_id = d_id
    dp.d_name = params['name']
    dp.d_desc = params['desc']
    dp.belongs = Users.objects.get(account=account)
    dp.model_which = bool(int(params['model']['which']))
    dp.opt_target = int(params['opt_target'])
    dp.summer_day = params['summer_day']
    dp.winter_day = params['winter_day']
    dp.model_buy_gas = bool(int(params['model']['buy_gas']))
    dp.model_buy_heat = bool(int(params['model']['buy_heat']))
    dp.cchp_is_selected = bool(int(params['CCHP']['is_selected']))

    max_power = params['CCHP']['parameter']['max_power']
    dp.cchp_max_power = float(max_power) if dp.cchp_is_selected and max_power else 0
    dp.ars_is_selected = bool(int(params['CCHP']['ARS']['is_selected']))

    if dp.ars_is_selected:
        which_ar = params['CCHP']['ARS']['which']
        dp.ars_which = which_ar if which_ar else ARS.objects.get(is_default=True).model_name
    else:
        dp.ars_which = ''

    dp.ice_is_selected = bool(int(params['CCHP']['ICE']['is_selected']))

    if dp.ice_is_selected:
        which_ice = params['CCHP']['ICE']['which']
        dp.ice_which = which_ice if dp.ice_which else ICE.objects.get(is_default=True).model_name
    else:
        dp.ice_which = ''

    dp.gt_is_selected = bool(int(params['CCHP']['gt']['is_selected']))

    if dp.gt_is_selected:
        which_gt = params['CCHP']['gt']['which']
        dp.gt_which = which_gt if dp.gt_which else GasTurbine.objects.get(is_default=True).model_name
    else:
        dp.gt_which = ''

    dp.ar_is_selected = bool(int(params['ar']['is_selected']))

    if dp.ar_is_selected:
        which_ar = params['ar']['which']
        dp.ar_which = which_ar if which_ar else AR.objects.get(is_default=True).model_name
    else:
        dp.ar_which = ''

    dp.re_is_selected = bool(int(params['re']['is_selected']))
    dp.wind_is_selected = bool(int(params['re']['wind']['is_selected']))
    if dp.wind_is_selected:
        which_wind = params['re']['wind']['which']
        dp.wind_which = which_wind if which_wind else WindPower.objects.get(is_default=True).model_name
    else:
        dp.wind_which = ''

    dp.solar_is_selected = bool(int(params['re']['solar']['is_selected']))
    if dp.solar_is_selected:
        which_solar = params['re']['solar']['which']
        dp.solar_which = which_solar if which_solar else PVP.objects.get(is_default=True).model_name
    else:
        dp.solar_which = ''
    dp.hp_is_selected = bool(int(params['hp']['is_selected']))
    dp.gp_is_selected = bool(int(params['hp']['gp']['is_selected']))
    if dp.gp_is_selected:
        which_gp = params['hp']['gp']['which']
        dp.gp_which = which_gp if which_gp else GroundPump.objects.get(is_default=True).model_name
    else:
        dp.gp_which = ''
    max_power = params['hp']['gp']['parameter']['max_power']
    dp.gp_max_power = float(max_power) if max_power and dp.gp_is_selected else 0
    dp.ap_is_selected = bool(int(params['hp']['ap']['is_selected']))
    if dp.ap_is_selected:
        which_ap = params['hp']['ap']['which']
        dp.ap_which = which_ap if which_ap else AirPump.objects.get(is_default=True).model_name
    else:
        dp.ap_which = ''

    max_power = params['hp']['ap']['parameter']['max_power']
    dp.ap_max_power = float(max_power) if max_power and dp.ap_is_selected else 0

    dp.boiler_is_selected = bool(int(params['boiler']['is_selected']))
    dp.gb_is_selected = bool(int(params['boiler']['gb']['is_selected']))
    if dp.gb_is_selected:
        which_gb = params['boiler']['gb']['which']
        dp.gb_which = which_gb if which_gb else GasBoiler.objects.get(is_default=True).model_name
        dp.gb_max_power = params['boiler']['gb']['parameter']['max_power'] if params['boiler']['gb']['parameter']['max_power'] else 0
    else:
        dp.gb_which = ''
        dp.gb_max_power = 0

    dp.eb_is_selected = bool(int(params['boiler']['eb']['is_selected']))

    if dp.eb_is_selected:
        which_eb = params['boiler']['eb']['which']
        dp.eb_which = which_eb if which_eb else ElectricBoiler.objects.get(is_default=True).model_name
        dp.eb_max_power = params['boiler']['eb']['parameter']['max_power'] if params['boiler']['eb']['parameter']['max_power'] else 0
    else:
        dp.eb_which = ''
        dp.eb_max_power = 0

    dp.ese_is_selected = bool(int(params['ese']['is_selected']))
    dp.ice_storage_is_selected = bool(int(params['ese']['ice_storage']['is_selected']))
    max_cap = params['ese']['ice_storage']['parameter']['max_capacity']
    dp.ice_storage_max_capacity = max_cap if dp.ice_storage_is_selected and max_cap else 0
    max_cap = params['ese']['ice_storage']['parameter']['max_capacity']
    dp.ice_storage_max_power = max_cap if dp.ice_storage_is_selected and max_cap else 0
    dp.cu_is_selected = bool(int(params['ese']['ice_storage']['cu']['is_selected']))
    if dp.cu_is_selected:
        which_cu = params['ese']['ice_storage']['cu']['which']
        dp.cu_which = which_cu if which_cu else ERU.objects.get(is_default=True).model_name
    else:
        dp.cu_which = ''
    dp.it_is_selected = bool(int(params['ese']['ice_storage']['it']['is_selected']))
    if dp.it_is_selected:
        which_it = params['ese']['ice_storage']['it']['which']
        dp.it_which = which_it if which_it else IceTank.objects.get(is_default=True).model_name
    else:
        dp.it_which = ''
    dp.heat_storage_is_selected = bool(int(params['ese']['heat_storage']['is_selected']))

    cap = params['ese']['heat_storage']['parameter']['max_capacity']
    dp.heat_storage_max_capacity = float(cap) if dp.heat_storage_is_selected and cap else 0
    ch = params['ese']['heat_storage']['parameter']['max_powerch']
    dp.heat_storage_max_powerch = float(ch) if dp.heat_storage_is_selected and ch else 0
    dis = params['ese']['heat_storage']['parameter']['max_powerdis']
    dp.heat_storage_max_powerdis = float(dis) if dp.heat_storage_is_selected and dis else 0
    eff = params['ese']['heat_storage']['parameter']['efficiency']
    dp.heat_storage_efficiency = float(eff) if dp.heat_storage_is_selected and eff else 0
    dp.ele_storage_is_selected = bool(int(params['ese']['ele_storage']['is_selected']))
    cap = params['ese']['ele_storage']['parameter']['max_capacity']
    dp.ele_storage_max_capacity = float(cap) if dp.ele_storage_is_selected and cap else 0
    dp.battery_is_selected = bool(int(params['ese']['ele_storage']['battery']['is_selected']))
    if dp.battery_is_selected:
        which_battery = params['ese']['ele_storage']['battery']['which']
        dp.battery_which = which_battery if which_battery else Buttery.objects.get(is_default=True).model_name
    else:
        dp.battery_which = ''

    dp.save()


@session_check
def show_cal_params(request):
    """
    根据用户的账号和get中传入的具体某次规划的id进行查看具体计算的配置信息
    :param request:
    :return:
    """
    who = request.COOKIES.get('who', '')
    which = request.GET.get('which', '')
    return render(request, 'users/project_params.html', {"params": DesignPlan.objects.get(design_id=which, belongs__account=who)})


@session_check
def show_his_params(request):
    """
    返回历史配置信息的列表
    :param request:
    :return:
    """
    who = request.COOKIES.get('who', '')

    designs = DesignPlan.objects.filter(belongs__account=who).values('d_name', 'time', 'design_id', 'wind_is_selected',
                                                                     'solar_is_selected').order_by('-time')

    return render(request, 'users/cal_history.html', {'designs': designs})


@session_check
def show_temp_day(request):
    """
    用于处理典型日中的相关数据，通过获取数据库中的历史结果，进行汇总统计后返回给前端展示
    :param request:
    :return:
    """
    who = request.COOKIES.get('who', '')
    which = request.GET.get('which', '')
    if not which:
        which = DesignPlan.objects.filter(belongs__account=who).order_by('-design_id')[0].design_id
    try:
        design = DesignPlan.objects.values('summer_day', 'winter_day', 'gt_which',
                                           'ice_which', 'gp_which', 'ap_which', 'gb_which', 'ar_which', 'eb_which', 'cu_which',
                                           'wind_which', 'solar_which').get(belongs__account=who, design_id=which)
    except Exception as e:
        print(e)
        return HttpResponse('')

    table_head = ['日期', '时间', 'CCHP发电', 'GSHP供热', 'GSHP供冷', 'ACHP供冷', 'GB供热',
                  'AR供冷', 'EB供热', '冰蓄冷', '购电量', '购电费', '购气量', '购气费', '购热量', '购热费', '售电',
                  '售电收入', '风机', '光伏板', 'CCHP供热', 'CCHP供冷']

    all_data = CalResult.objects.filter(design_id=which)

    winter_day = all_data.filter(target_date=design['winter_day'])
    summer_day = all_data.filter(target_date=design['summer_day'])

    # 首先定义汇总信息的保存变量
    summary = {}
    # 其次，通过聚合函数获取到数据库中已经计算好的结果的求和信息
    sum_data = all_data.aggregate(ele_buy=Sum('ele_buy'), gas_buy=Sum('gas_buy'),
                                  heat_buy=Sum('heat_buy'),
                                  wind_power=Sum('wind_power'), pvp_power=Sum('pvp_power'),
                                  sell_e=Sum('sell_e'),
                                  sell_h=Sum('sell_h'), sell_c=Sum('sell_c'), ele_inc=Sum('ele_inc'),
                                  heat_load=Sum('heat_load'),
                                  cold_load=Sum('cold_load'), ele_load=Sum('ele_load'),
                                  ele_sell=Sum('ele_sell'), ele_pri=Sum('ele_pri'), gas_pri=Sum('gas_pri'),
                                  heat_pri=Sum('heat_pri'), ice_os=Sum('ice_os'), gp_ieh=Sum('gp_ieh'),
                                  ap_ie=Sum('ap_ie'), gb_ig=Sum('gb_ig'), ar_ig=Sum('ar_ig'),
                                  eb_ie=Sum('eb_ie'), eru=Sum('it_ch'), wind=Max('wind'), pvp=Sum('PV'), co2_em=Sum('co2_em'),
                                  nox_em=Sum('nox_em'))

    # for k, v in sum_data.items():
    #     if v is None:
    #         sum_data[k] = 0

    # 汇总数据
    #     summary = {
    #         "year_of_system": 7307815,  # 系统年费用
    #         "invest": 32245000,  # 投资折合费用
    #         "opration": 5481650,  # 运行维护费用
    #         'fuel': 159531508,  # 燃料购置费用
    #         'income': 189950343,  # 售能收益
    #         'energy_cons': 292621973,  # 一次能耗
    #         'pv_diff_ele': 100,  # 峰谷差占最大负荷比
    #         'pv_diff_heat': 91,
    #         'pv_diff_cold': 100,
    #         'e_eff': 127,  # 能源利用率
    #         'ce_generation': 0,  # 清洁能源发电占比
    #         'a_rate_wind': '/',  # 弃风率
    #         'a_rate_light': '/'  # 弃光率
    #     }

    # 以下summary[xxx]为汇总信息中具体的某个汇总数据，对应名称如上所示
    summary['co2_em'] = sum_data['co2_em'] / 1000 if sum_data['co2_em'] else 0
    summary['nox_em'] = sum_data['nox_em'] / 1000 if sum_data['nox_em'] else 0

    summary['energy_cons'] = (sum_data['ele_buy'] + sum_data['gas_buy'] + sum_data['heat_buy']) / 1000

    summary['e_eff'] = ((sum_data['heat_load'] + sum_data['cold_load'] + sum_data['ele_load'] + sum_data['ele_sell']) / 10) / summary[
        'energy_cons']

    summary['ce_generation'] = (sum_data['wind_power'] + sum_data['pvp_power']) / (
            sum_data['ele_buy'] + sum_data['wind_power'] + sum_data['pvp_power'])

    summary['income'] = (sum_data['sell_e'] + sum_data['sell_h'] + sum_data['sell_c'] + sum_data['ele_inc']) / 10000

    summary['fuel'] = (sum_data['ele_pri'] + sum_data['gas_pri'] + sum_data['heat_pri']) / 10000

    result = {'table_head': table_head, "winter_day": winter_day, "summer_day": summer_day, 'which': which, 'summary': summary}

    if design['gt_which'] and not design['ice_which']:
        ccph_pri = GasTurbine.objects.get(model_name=design['gt_which']).ppp * sum_data['ice_os']
    elif not design['gt_which'] and design['ice_which']:
        ccph_pri = ICE.objects.get(model_name=design['ice_which']).ppp * sum_data['ice_os']
    else:
        ccph_pri = 0

    if design['gp_which']:
        gp_pri = GroundPump.objects.get(model_name=design['gp_which']).ppp * sum_data['gp_ieh']
    else:
        gp_pri = 0

    if design['ap_which']:
        ap_pri = AirPump.objects.get(model_name=design['ap_which']).ppp * sum_data['ap_ie']
    else:
        ap_pri = 0

    if design['gb_which']:
        gb_pri = GasBoiler.objects.get(model_name=design['gb_which']).ppp * sum_data['gb_ig']
    else:
        gb_pri = 0

    if design['ar_which']:
        ar_pri = AR.objects.get(model_name=design['ar_which']).ppp * sum_data['ar_ig']
    else:
        ar_pri = 0

    if design['eb_which']:
        eb_pri = ElectricBoiler.objects.get(model_name=design['eb_which']).ppp * sum_data['eb_ie']
    else:
        eb_pri = 0

    if design['cu_which']:
        eru_pri = ERU.objects.get(model_name=design['cu_which']).ppp * sum_data['eru']
    else:
        eru_pri = 0

    if design['wind_which']:
        wind_pri = WindPower.objects.get(model_name=design['wind_which']).ppp * sum_data['wind']
    else:
        wind_pri = 0

    if design['solar_which']:
        pvp_pri = PVP.objects.get(model_name=design['solar_which']).ppp * sum_data['pvp']
    else:
        pvp_pri = 0
    summary['invest'] = ((ccph_pri + gp_pri + ap_pri + gb_pri + ar_pri + eb_pri + eru_pri + pvp_pri) / 8760 + wind_pri) / 10000

    summary['opration'] = summary['invest'] * 0.17

    summary['year_of_system'] = summary['invest'] + summary['opration'] + summary['fuel'] - summary['income']
    return render(request, 'users/data_content.html', result)


def delete_his_cal(request):
    ask = json.loads(str(request.body, encoding='UTF-8'))
    target_id = ask['id']
    rsp = {
        'code': 200,
        'msg': 'ok'
    }
    try:
        root_path = os.path.join(STATIC_ROOT + '/business/user_params_file/')
        all_files = os.listdir(root_path)
        for item in all_files:
            if target_id in item:
                os.remove(os.path.join(root_path, item))

        CalResult.objects.filter(design_id=target_id).delete()
        DesignPlan.objects.filter(design_id=target_id).delete()
    except Exception as e:
        print(e)
        rsp['code'] = 500
        rsp['msg'] = '程序内部出现异常，请联系管理员'
    return JsonResponse(rsp)
